package cn.sfinger.huifu.p2p.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public final class HttpClientUtil {
	private static final Logger log= LoggerFactory.getLogger(HttpClientUtil.class);
	
	private static HttpClientUtil instance;
	private String urlCharset;
	
	/**
	 * 得到指定url字符编码的实例
	 * @param urlCharset
	 * @return
	 */
	public static HttpClientUtil getInstantce(String urlCharset){
		if(instance == null){
			instance= new HttpClientUtil();
		}
		instance.setUrlCharset(urlCharset);
	
		return instance;
	}
	/**
	 * 默认得到url为UTF-8编码的实例
	 * @return
	 */
	public static HttpClientUtil getInstantce(){
		return getInstantce("UTF-8");
	}
	
	public JSONObject getPostResponseAsJSON(String url, Map<String, Object> params){
		return JSON.parseObject(getPostResponse(url, params));
	}
	
	/**
	 * 获取应答报文，以String形式返回
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public String getPostResponse(String url, Map<String, Object> params){
		String respStr= "";
		try{
			List<NameValuePair> paramPairs= new ArrayList <NameValuePair>();
			
			for(String key: params.keySet()){
				paramPairs.add(new BasicNameValuePair(key, (String)params.get(key)));
			}
			
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(paramPairs));
			CloseableHttpResponse response = httpclient.execute(httpPost);
			
			try{
				HttpEntity entity = response.getEntity();
				respStr= EntityUtils.toString(entity);
				EntityUtils.consume(entity);
			}catch(Exception e){
				log.error("HTTP request failed! [URL]:{},[PARAMETERS]:{}",url,JSON.toJSONString(params));
				log.error(e.getMessage());
			}
			finally{
				response.close();
			}
		}catch(Exception e){
			log.error("HTTP request failed! [URL]:{},[PARAMETERS]:{}",url,JSON.toJSONString(params));
			log.error(e.getMessage());
		}
		
		return respStr;
	}
	
	public String getUrlCharset() {
		return urlCharset;
	}
	public void setUrlCharset(String urlCharset) {
		this.urlCharset = urlCharset;
	}
}
